import os

from django.contrib.auth.models import User
from django.db.models import F
from django.http import HttpResponse, FileResponse
from django.shortcuts import render, redirect, get_object_or_404

from Login_regist.models import UserDetails
from chat.models import Post
from learning_learning.settings import MEDIA_URL
from resources.models import Classes, Books, Label, Courses, CouCom, BookCom, Collections, History
from django.shortcuts import render
from django.http import JsonResponse


# Create your views here.

def recommend(request,**kwargs):
    #从请求中获取classes和sort
    classes = kwargs.get('classes')
    sort = kwargs.get('sort')
    try:
        res = Classes.objects.get(name=classes)
    except Classes.DoesNotExist:
        return redirect('not_find')
    if sort == '课程':
        resources = res.course_classes.all()
    if sort == '书籍':
        resources = res.book_classes.all()
    if sort == '博客':
        resources = res.article_classes.all()

    return HttpResponse(render(request,'templates/LR/recommend.html',
                               context={
                                   'sort' : ['课程','书籍','博客'],
                                   'resources' : resources,
                                   'now_cls':classes,
                                   'classes':Classes.objects.all(),
                                   'username':request.user.username,
                               }
                               ))


def learning_center(request,**kwargs):
    """ 渲染学习中心页面 """
    classes = Classes.objects.all() # 数一 数二 数三
    subjects = Label.objects.values('name').distinct()    # 显示对应考试的科目
    teachers = Books.objects.values_list('teacher',flat=True).distinct()    # 对应考试的老师
    resources = Books.objects.all()  # 默认显示对应科目的所有书籍
    user = User.objects.get(username=request.user)
    userdetails = UserDetails.objects.get(user=user)
    return render(request, 'templates/resources/learning_center.html', {
        'username': request.user.username,
        'classes': classes,
        'subjects':subjects,
        'teachers':teachers,
        "BorC": ['书籍', '课程'],
        "resources": resources,
        'user': userdetails,
    })


def filter_resources(request):
    """ 处理筛选请求，返回 JSON 数据 """
    selected_class = request.GET.get("class", "")  # 获取选中的分类
    selected_subject = request.GET.get("sub", "")  # 获取选中的分类
    selected_teacher = request.GET.get("tea", "")  # 获取选中的分类
    selected_type = request.GET.get("type", "")    # 书籍 or 课程

    selected_subject = selected_subject.strip("{}")
    subject_name = selected_subject.split(": ")[1].strip("'")

    # 过滤数据
    if selected_class and selected_subject:
        if selected_type =='书籍':
            resources = Books.objects.filter(classes__name=selected_class,label__name=subject_name,teacher = selected_teacher)
            res_type = 'books'
        else:
            resources = Courses.objects.filter(classes__name=selected_class,label__name=subject_name,teacher = selected_teacher)
            res_type = 'courses'
    else:
        resources = Books.objects.all()

    # 转换数据为 JSON 格式
    resource_list = [
        {
            "id":r.id,
            "title": r.title,
            "desc": r.desc,
            "create_time": r.create_time.strftime('%Y-%m-%d'),
            "cover": r.cover,
            "type": res_type,
        }
        for r in resources
    ]

    return JsonResponse({"resources": resource_list})


def resource_detail(request,res_type,id):
    user = UserDetails.objects.get(user=request.user)
    if res_type == 'books':
        try:
            res = Books.objects.get(id=id)
            Books.objects.filter(id=id).update(page_view=F('page_view')+1)
            parent_comments = BookCom.objects.filter(books=res, parent_comment__isnull=True).order_by('-created_at')
            comment_data = []
            for parent in parent_comments:
                children = BookCom.objects.filter(parent_comment=parent).order_by('-created_at')
                parent_userdetails = UserDetails.objects.get(user=parent.user)
                comment_data.append({
                    'parent': parent,
                    'children': children,
                    'userdetails': parent_userdetails,
                })
        except Courses.DoesNotExist:
            return redirect('not_find')
    else:
        try:
            res = Courses.objects.get(id=id)
            Courses.objects.filter(id=id).update(page_view=F('page_view') + 1)
            parent_comments = CouCom.objects.filter(courses=res, parent_comment__isnull=True).order_by('-created_at')
            comment_data = []
            for parent in parent_comments:
                children = CouCom.objects.filter(parent_comment=parent).order_by('-created_at')
                parent_userdetails = UserDetails.objects.get(user=parent.user)
                comment_data.append({
                    'parent': parent,
                    'children': children,
                    'userdetails': parent_userdetails,
                })
        except Courses.DoesNotExist:
            return redirect('not_find')

    return HttpResponse(render(request,f'templates/resources/{res_type}.html',{
        'resource':res,
        'username': request.user.username,
        'comments_data':comment_data,
        'user':user,
    }))

def book_preview(request,book_id):
    try:
        book = get_object_or_404(Books, id=book_id)
        file_name = f"book/{book.content}"
        file_path = os.path.join(MEDIA_URL, file_name)
        return FileResponse(open(file_path, 'rb'),content_type='application/pdf')
    except Books.DoesNotExist:
        return redirect('not_find')

    # return render(request,'templates/resources/book_preview.html',{'book':book,'file_path':file_path})

def book_download(request,book_id):
    book = get_object_or_404(Books, id=book_id)
    file_name = f"book/{book.content}"
    file_path = os.path.join(MEDIA_URL, file_name)
    return FileResponse(open(file_path,'rb'),as_attachment=True,filename=book.title + '.pdf')

def load_child_comments(request,res_type,parent_id):
    """
    异步加载子级评论
    :param request:
    :param id:
    :return:
    """
    if res_type == 'courses':
        parent = get_object_or_404(CouCom, id=parent_id)
        child_comments = CouCom.objects.filter(parent_comment=parent).order_by('-created_at')

        child_comments_list = [
            {
                'username': c.user.username,
                'content': c.content,
                'created_at': c.created_at.strftime('%Y-%m-%d %H:%M'),
                'child_comments': list(
                    CouCom.objects.filter(parent_comment=c).order_by('-created_at').values('id', 'user_id', f'{res_type}_id',
                                                                                            'content', 'parent_comment_id',
                                                                                            'created_at')),
                'cover': UserDetails.objects.get(user=c.user).cover,
                'id': c.id,

            }
            for c in child_comments
        ]
    else :
        parent = get_object_or_404(BookCom, id=parent_id)
        child_comments = BookCom.objects.filter(parent_comment=parent).order_by('-created_at')

        child_comments_list = [
            {
                'username': c.user.username,
                'content': c.content,
                'created_at': c.created_at.strftime('%Y-%m-%d %H:%M'),
                'child_comments': list(
                    BookCom.objects.filter(parent_comment=c).order_by('-created_at').values('id', 'user_id',
                                                                                           'books_id',
                                                                                           'content',
                                                                                           'parent_comment_id',
                                                                                           'created_at')),
                'cover': UserDetails.objects.get(user=c.user).cover,
                'id': c.id,

            }
            for c in child_comments
        ]
    return JsonResponse({'child_comments': child_comments_list})

def footprint(request,**kwargs):
    """
    type id cover title desc create_at
    :param request:
    :param collection_id:
    :return:
    """
    key = kwargs.get('key')
    if key == 'collection':
        favorites = Collections.objects.filter(user=request.user)
    elif key == 'history':
        favorites = History.objects.filter(user=request.user)
    resources = []

    for favorite in favorites:
        if favorite.posts:
            res_type = 'posts'
            res = Post.objects.get(id=favorite.posts_id)
        if favorite.books:
            res_type = 'books'
            res = Books.objects.get(id=favorite.books_id)
        if favorite.courses:
            res_type = 'courses'
            res = Courses.objects.get(id=favorite.courses_id)
        resources.append({
            'id': res.id,
            'res_type': res_type,
            'title': res.title,
            'desc': res.desc,
            'cover':res.cover,
            'create_time': favorite.create_time.strftime('%Y-%m-%d %H:%M'),
        })

    return HttpResponse(render(request,'templates/resources/collection.html',
                               context={
                                   'resources': resources,
                               }))

